<template>
  <div>
    <!-- 新增 -->
    <a-modal :width="600" :visible="visible" :confirm-loading="loading" :forceRender="true" :maskClosable="false"
      :title="isUpdate ? '编辑分类' : '添加分类'" :body-style="{ paddingBottom: '8px' }" @update:visible="updateVisible"
      @ok="save" @close="updateVisible(false)">
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ md: { span: 5 }, sm: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <!-- <a-form-item label="最后一层:" name="type">
          <a-select v-model:value="form.type">
            <a-select-option value="N">否</a-select-option>
            <a-select-option value="Y">是</a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="分类名称:" name="style">
          <a-input v-model:value="form.style" placeholder="请输入分类名称" allow-clear @input="handleInput" autocomplete="off"
            :maxlength="32" />
        </a-form-item>
        <a-form-item label="包含标签:" name="styleList">
          <!-- <a-tree-select v-if="!isUpdate" v-model:value="form.styleList" style="width: 100%" :tree-data="orgList"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择上级机构" :fieldNames="{
      children: 'children',
      label: 'name',
      key: 'tagStyleNo',
      value: 'tagStyleNo',
    }" allow-clear tree-default-expand-all /> -->

          <a-select v-model:value="form.styleList" mode="multiple" :filter-option="filterOption" style="width: 100%"
            placeholder="选择标签（多选）" :option-label-prop="label" @change="handleChange">
            <a-select-option v-for=" item in styleListOptions" :key="item.value" :value="item.value"
              :label="item.label">
              {{ item.label }}
            </a-select-option>

          </a-select>
          <!-- <a-tree-select v-else ref="treeSelectRef" :disabled="form.parentNo === '-1'" v-model:value="form.parentNo"
            style="width: 100%" :tree-data="orgList" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择上级机构" :fieldNames="{
      children: 'children',
      label: 'name',
      key: 'tagStyleNo',
      value: 'tagStyleNo',
    }" allow-clear tree-default-expand-all :key="treeSelectKey" @change="handleSelectChange" /> -->
        </a-form-item>


        <!-- <a-form-item label="新旧:" name="newFlagChecked">
          <a-switch
            checked-children="是"
            un-checked-children="否"
            v-model:checked="newFlagChecked"
          />
        </a-form-item> -->

        <!-- <a-form-item label="热门:" name="hotFlagChecked">
          <a-switch
            checked-children="是"
            un-checked-children="否"
            v-model:checked="hotFlagChecked"
          />
        </a-form-item> -->

        <!-- <a-form-item label="图片上传:">
          <a-upload
            :action="uploadUrl"
            :multiple="true"
            :file-list="fileList"
            name="file"
            :data="extraData"
            @change="handleUploadChange"
          >
              <a-button>
                <upload-outlined></upload-outlined>
                上传
              </a-button>
          </a-upload>
        </a-form-item> -->

        <a-form-item label="图片上传:" name="imageFileId">
          <a-upload name="file" :multiple="true" :maxCount="1" :action="FileUploadUrlToDb" :headers="headers"
            :before-upload="beforeUpload" v-model:file-list="fileList" @change="afterUpload" list-type="picture"
            @preview="handlePreview" :showUploadList="showUploadList">

            <a-button>
              <template #icon>
                <CloudUploadOutlined />
              </template>
              <span>上传</span>
            </a-button>
          </a-upload>
          <a-modal v-model:visible="previewVisible" :title="previewTitle" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue/es';
import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import useFormData from '/@/utils/common/use-form-data';
import { useUserStore } from '/@/store/modules/user';
import { TagStyleInfoApi } from '/@/api/touch/tagStyle/TagStyleInfoApi';
import { StyleInfoApi } from '/@/api/touch/styleInfo/StyleInfoApi';
import { TagStyleInfoRequest } from '/@/api/touch/tagStyle/model/TagStyleInfoModel';
import { FileApi, FileUploadUrl } from '/@/api/system/operation/FileApi';
import Unauthorized from 'ant-design-vue/lib/result/unauthorized';

const emit = defineEmits<{
  (e: 'done'): void;
  (e: 'update:visible', value: boolean): void;
}>();

const props = defineProps<{
  // 弹窗是否打开
  visible: boolean;
  // 是否是修改
  isUpdate: false;
  // 修改回显的数据
  data?: Object;
  // 组织机构列表
  orgList: Array<{ id: string; name: string; children?: Array<any> }>;
}>();
// 组织列表
const orgLists = ref(props.orgList);

// 强制刷新组件的 key
const treeSelectKey = ref(0);
// 表单实例
const formRef = ref<FormInstance | null>(null);
// 提交状态
const loading = ref<boolean>(false);
// newFlag check
const newFlagChecked = ref<boolean>(false);
const hotFlagChecked = ref<boolean>(false);
const fileList = ref([]);
const styleListOptions = ref([])

const showUploadList = ref<boolean>(false);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
// 表单数据
let { form, resetFormFields } = useFormData<TagStyleInfoRequest>({
  imageFileId: undefined,
  style: undefined,
  type: 'FL',
  parentNo: '-1',
  styleList: []
});

// 表单验证规则
const rules = reactive({
  style: [{ required: true, message: '请输入分类名称', type: 'string', trigger: 'change' }],
  // imageFileId: [{ required: true, message: '请上传文件', type: 'string', trigger: 'change' }],
  styleList: [{ required: true, message: '请选择标签', type: 'array', trigger: 'change' }],
});
const handleChange = value => {

  console.log(`selected ${value}`);
};
watch(
  () => props.visible,
  () => {
    console.log('props.visible', props.visible);
    if (!props.visible) {
      resetFormFields();
      formRef.value?.clearValidate();
      fileList.value = [];
    } else {
      if (Object.keys(props.data || {}).length === 0) {
        resetFormFields();
        formRef.value?.clearValidate();
        fileList.value = [];
      } else {
        form = ref({ ...props.data })
        form.value.styleList = props.data.styleNoList !== '' ? props.data.styleNoList.split(',') : []
        showUploadList.value = true;
        fileList.value = [{
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: form.value.imageFileId,
        }];
        form.value.imageFileId = undefined
      }
    }
    getList()
  },
);

// 根据 isNew 切换表单数据

// 上传文件的url（上传到数据库）
const FileUploadUrlToDb = ref<string>(
  `${import.meta.env.VITE_GLOB_API_URL}${FileUploadUrl}?secretFlag=N&fileLocation=5`,
);
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }

  previewImage.value = file.url || file.preview;
  console.log(previewImage, '111');

  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {

    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
const userStore = useUserStore();
const token = computed(() => {
  return userStore.getToken;
});
const headers = reactive({
  Authorization: token.value,
});
const filterOption = (input, option) => {

  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
/**
 * 控制上传到数据库的图片不能超过1M
 *
 * @author fengshuonan
 * @date 2021/4/12 22:29
 */
const beforeUpload = (file: any) => {
  const isLt2M = file.size / 1024 / 1024 <= 2;
  if (!isLt2M) {
    message.error('上传图片不能超过2MB');
  }
  return isLt2M;
};

/**
 * 上传成功的回调
 *
 * @author fengshuonan
 * @date 2021/4/2 17:03
 */
const afterUpload = ({ file }) => {
  showUploadList.value = true;
  loading.value = true;
  if (file.response) {
    message.success('上传成功');
    loading.value = false;
    if (!props.isUpdate) {
      form.imageFileId = file.response.data.fileId;
    } else {
      form.value.imageFileId = file.response.data.fileId;
    }
  }
};
const treeSelectRef = ref(null);
const handleSelectChange = (value: string, label, node) => {
  console.log('value', value, node, label);
  treeSelectKey.value++;
};
// token
const handleInput = (event) => {
  console.log('event', event);
  const maxLength = 32;
  if (event.target.value.length > maxLength) {
    form.style = event.target.value = event.target.value.slice(0, maxLength);
  }
};
/* 
定义一个写接口的方法
 */

const getList = async () => {
  await StyleInfoApi.styleInfoList({ type: "FL" }).then(res => {
    console.log(res, 'res');
    styleListOptions.value = res
    styleListOptions.value = res.map(item => {
      return { label: item.name, value: item.styleNo }
    })
    console.log();

  })
}

/**
 * 保存编辑
 *
 */
const save = () => {
  // 校验表单
  if (!formRef.value) {
    return;
  }
  formRef.value.validate().then((valid) => {
    form.type = 'FL'
    if (valid) {
      // if (newFlagChecked.value === true) {
      //   form.newFlag = 'Y';
      // } else {
      //   form.newFlag = 'N';
      // }
      // if (hotFlagChecked.value === true) {
      //   form.hotFlag = 'Y';
      // } else {
      //   form.hotFlag = 'N';
      // }

      // // 获取已上传图片的fileId
      // form.imageFileId = imageFileId.value;
      // 修改加载框为正在加载
      loading.value = true;
      // 执行新增保存
      if (props.isUpdate) {
        form.value.styleNoList = form.value.styleList.join(',');
        TagStyleInfoApi.edit(form.value).then((result) => {
          // 移除加载框
          loading.value = false;
          // 提示添加成功
          message.success(result.message);
          // 关闭弹框，通过控制visible的值，传递给父组件
          updateVisible(false);
          // 触发父组件done事件
          emit('done');
          // 重置表单字段
          resetFormFields();
          formRef.value?.clearValidate();
          formRef.value?.resetFields();
          showUploadList.value = false; // 清空已上传的文件列表
          // form = {};

          // form = {
          //   imageFileId: undefined,
          //   style: undefined,
          //   newFlag: undefined,
          //   hotFlag: undefined,
          // };
          // 重置表单数据和状态
        });
      } else {

        form.styleNoList = form.styleList.join(',');
        TagStyleInfoApi.add(form)
          .then((result) => {
            // 移除加载框
            loading.value = false;
            // 提示添加成功
            message.success(result.message);
            // 关闭弹框，通过控制visible的值，传递给父组件
            updateVisible(false);
            // 触发父组件done事件
            emit('done');
            // 重置表单字段
            resetFormFields();
            formRef.value?.clearValidate();
            formRef.value?.resetFields();

            showUploadList.value = false; // 清空已上传的文件列表
            // 重置表单数据和状态
          })
          .catch(() => {
            loading.value = false;
          });
      }
    }
  });
};

/**
 * 更新编辑菜单界面的弹框是否显示
 *
 * @param value true-显示，false-隐藏
 * @author jiawei
 * @date 2021/4/7 12:00
 */

const updateVisible = (value: boolean) => {
  emit('update:visible', value);
  resetFormFields();
  formRef.value?.clearValidate();
  showUploadList.value = false;

  Object.keys(form).forEach((key) => {
    form[key] = undefined;
  });
};
</script>
